package com.practice.gmall.realtime.app;

import com.practice.gmall.realtime.util.FlinkSourceUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public abstract class BaseApp {


    public void init(Integer port, String appNameAndPathAndGroupId, Integer parallelism, String brokers, String topic) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);
        conf.setString("pipeline.name",appNameAndPathAndGroupId);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

        env.setParallelism(parallelism);
        env.setStateBackend(new HashMapStateBackend());
        env.enableCheckpointing(3000L);
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/gmall/"+appNameAndPathAndGroupId);
        env.getCheckpointConfig().setCheckpointTimeout(60*1000);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);


        DataStreamSource<String> stream = env.fromSource(FlinkSourceUtil.getKafkaSource(brokers,topic,appNameAndPathAndGroupId), WatermarkStrategy.noWatermarks(), "kafka source: " + appNameAndPathAndGroupId);

        handle(env,stream);

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    protected abstract void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream);

}
